/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Jun 8, 2012  1:21:36 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : apps.promis.out.construction
 * File Name : AccountPayableVoucherAction.java
 * TODO
 */
package apps.promis.in.construction;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import jpa.entitys.promis.common.Company;
import jpa.entitys.promis.common.CostProject;
import jpa.entitys.promis.common.SupplierMaster;
import jpa.entitys.promis.construction.AccountPayableVoucher;
import jpa.entitys.promis.construction.AccountPayableVoucherPK;
import jpa.entitys.promis.construction.ProjectAccountCost;
import jpa.entitys.promis.construction.ProjectAccountCostPK;
import jpa.entitys.promis.construction.VwSyncGrnItem;
import jpa.entitys.synchro.staging.MmSuppdebitnotesinb;
import jpa.service.promis.common.CompanyServices;
import jpa.service.promis.common.ProjectServices;
import jpa.service.promis.common.SupplierMasterServices;
import jpa.service.promis.construction.AccountPayableVoucherServices;
import jpa.service.promis.construction.ProjectAccountCostServices;
import jpa.service.promis.construction.VwSyncGrnItemServices;
import jpa.service.synchro.staging.MmSuppdebitnotesinbServices;

import org.apache.log4j.Logger;

import promis.utility.CommonService;
import promis.utility.Utilitys;
import apps.sessionFactory;

/**
 * 
 * @author Chatree Siangklom of Administrator
 * Date =Nov 13, 2013 : 2:38:45 PM 
 * CreateBy=Chatree Siangklom
 * 
 * AccountPayableVoucherAction
 * TODO
 */
public class AccountPayableVoucherAction {
		
	private static final Logger log = Logger.getLogger(AccountPayableVoucherAction.class);
	static MmSuppdebitnotesinbServices  MmSuppdebitnotesinbServ = null;
	static EntityManager  EmPromis;
	static EntityManager  EmSynchro;
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:38:51 PM 
	 * CreateBy=Chatree Siangklom
	 * AccountPayableVoucherAction
	 * TODO
	 * @throws Exception
	 */
	public AccountPayableVoucherAction() throws Exception {
		EmPromis = sessionFactory.CreateEmPromis();
		EmSynchro = sessionFactory.CreateEmSynchro();
		MmSuppdebitnotesinbServ = new MmSuppdebitnotesinbServices(EmSynchro);
	}	
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:38:54 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param args
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception {
		try{
			log.info("main --->");
			EmPromis = sessionFactory.CreateEmPromis();
			EmSynchro = sessionFactory.CreateEmSynchro();
			MmSuppdebitnotesinbServ = new MmSuppdebitnotesinbServices(EmSynchro);
			
			String instance_no = "10000000000002209634";
			
			List<MmSuppdebitnotesinb> lst = new MmSuppdebitnotesinbServices(EmSynchro).findByInstanceNoWithoutIsSync(instance_no);
			log.info("lst size = " + CommonService.getSize(lst));
			if(CommonService.getSize(lst) > 0)
			{
				//Create To Promis
				if(lst.get(0).getVoucherType().equals("AP")) //Account Payable (AP)
					new AccountPayableVoucherAction().CreateToPromis(lst);
				else if(lst.get(0).getVoucherType().equals("57")) //Credit Note (CN)
					new SupplierDebitNoteServicesAction().CreateToPromis(lst);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:38:58 PM 
	 * CreateBy=Chatree Siangklom
	 * PurchaseModel
	 * TODO
	 * @param company
	 * @param project
	 * @param po_document_no
	 * @return
	 * @throws Exception
	 */
	private PurchaseModel findPurchase(String company, String project, String po_document_no) throws Exception {
		try{
			StringBuffer _strQuery = new StringBuffer();

			_strQuery.append(" SELECT ");
			_strQuery.append(" COMPANY, PROJECT, PO_TYPE, PO_SERIES, PO_NO, NVL(REVISION_NO,0) AS REVISION_NO , ");
			_strQuery.append(" get_document_ref_no(PO_TYPE,PO_SERIES,PO_NO,REVISION_NO,'-') AS DOCUMENT_NO, STATUS ");
			_strQuery.append(" FROM PURCHASE_ORDERS ");
			_strQuery.append(" WHERE 1 = 1 ");			
			_strQuery.append(" AND COMPANY = ").append(Utilitys.strSql(company));
			_strQuery.append(" AND PROJECT = ").append(Utilitys.strSql(project ));
			_strQuery.append(" AND SYNC_EXTERNAL_REF_NO = ").append(Utilitys.strSql(po_document_no));
			_strQuery.append(" AND STATUS <> 'Z' ");
			
			System.out.println(_strQuery.toString());
			
			List<Object[]> result = (List<Object[]>)EmPromis.createNativeQuery(_strQuery.toString()).getResultList();
			 if(CommonService.getSize(result) > 0){
				 
				 for (Object[] resultElement : result) {
					 //String company = CommonService.IsNullRString(resultElement[0]);
					 //String project = CommonService.IsNullRString(resultElement[1]);
					 String poType = CommonService.IsNullRString(resultElement[2]);
					 String poSeries = CommonService.IsNullRString(resultElement[3]);
					 String poNo = CommonService.IsNullRString(resultElement[4]);
					 String revisionNo = CommonService.IsNullRString(resultElement[5]);
					 String documentNo = CommonService.IsNullRString(resultElement[6]);
					 String status = CommonService.IsNullRString(resultElement[7]);
					 
					 return new PurchaseModel(company, project, poType, poSeries, CommonService.ConvertStringToBigDecimal(poNo), CommonService.ConvertStringToBigDecimal(revisionNo), documentNo, status);
				 }
			 }
			 else {
				 System.out.println("Purchase Order No is [Nothing. SAP No : " + po_document_no + ", company:"+ company + ", project="+ project +"]");
				 log.error("Purchase Order No is [Nothing. SAP No : " + po_document_no + ", company:"+ company + ", project="+ project +"]");
				 throw new Exception("Purchase Order No is [Nothing. SAP No : " + po_document_no + ", company:"+ company + ", project="+ project +"]");
			 }
			 
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
		return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:39:05 PM 
	 * CreateBy=Chatree Siangklom
	 * AccountPayableVoucher
	 * TODO
	 * @param company
	 * @param project
	 * @param syncExternalRefNo
	 * @return
	 * @throws Exception
	 */
	private AccountPayableVoucher ExistsApprovedCheck(String company, String project, String syncExternalRefNo) throws Exception 
	{
		try{
			AccountPayableVoucherServices AccountPayableVoucherServ = new AccountPayableVoucherServices(EmPromis);
			List<AccountPayableVoucher> lst = AccountPayableVoucherServ.findBySapLivDocNo(company, project, syncExternalRefNo, "A");
			
			if(CommonService.getSize(lst) > 0)
				return lst.size() == 1 ? lst.get(0) : null;			
					
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
		return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:39:08 PM 
	 * CreateBy=Chatree Siangklom
	 * VwSyncGrnItem
	 * TODO
	 * @param company
	 * @param project
	 * @param documentNo
	 * @param unitNumber
	 * @param status
	 * @return
	 * @throws Exception
	 */
	private VwSyncGrnItem FindGRNBudgetByUnit(String company, String project ,String documentNo, String unitNumber, String status) throws Exception {
		try{
			
			VwSyncGrnItemServices grnService = new VwSyncGrnItemServices(EmPromis);
			List<VwSyncGrnItem> lst = grnService.findByDocumentItemByUnit(company, project, documentNo, unitNumber, status);
			
			if(CommonService.getSize(lst) > 0)
				return lst.get(0);
			
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());		
			throw e;
		}
		return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:39:12 PM 
	 * CreateBy=Chatree Siangklom
	 * AccountPayableVoucher
	 * TODO
	 * @param value
	 * @return
	 * @throws Exception
	 */
	private AccountPayableVoucher setHeader(MmSuppdebitnotesinb value) throws Exception {
		AccountPayableVoucher model = null;		
		try{
			AccountPayableVoucherServices AccountPayableVoucherServ = new AccountPayableVoucherServices(EmPromis);
			
			//Find Project Master
			CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
			String company = costProject.getId().getCompany();
			String project = costProject.getId().getProject();
			
			model =  ExistsApprovedCheck(company, project, value.getExtRefNo());
			if(model == null){
				if(value.getStatus().equals("A")){
					model = new AccountPayableVoucher();				
					AccountPayableVoucherPK id = new AccountPayableVoucherPK();
					id.setCompany(company);
					id.setVoucherType(value.getVoucherType());
					
					//Create New PO
					String series_no = AccountPayableVoucherServ.getPromisSeriesNext(company, project, value.getVoucherType(), CommonService.ConvertPmsStagingDateTime(value.getDocDate()));
					
					Long document_no = AccountPayableVoucherServ.getPromisDocumentNoNext(company, project, value.getVoucherType(), series_no);
					
					id.setProject(project);
					id.setVoucherNumber(document_no);
					id.setVoucherSeries(series_no);
					
					model.setId(id);	
				}else{					
					System.out.println("Can't Create Liv Document No = "+ value.getExtRefNo() +" is Status = "+ value.getStatus() +" fail.");
					log.error("Can't Create Liv Document No = "+ value.getExtRefNo() +" is Status = "+ value.getStatus() +" fail.");
					throw new Exception("Can't Create Liv Document No = "+ value.getExtRefNo() +" is Status = "+ value.getStatus() +" fail.");
				}
			}else
			{
				if(CommonService.IsNullRString(value.getStatus()).equals("A") && CommonService.IsNullRString(model.getStatus()).equals("A")){
					System.out.println("Exists Liv Document No = "+ value.getExtRefNo() +" Status = "+ value.getStatus() +" is Duplicate.");
					log.error("Exists Liv Document No = "+ value.getExtRefNo() +" Status = "+ value.getStatus() +" is Duplicate.");
					throw new Exception("Exists Liv Document No = "+ value.getExtRefNo() +" Status = "+ value.getStatus() +" is Duplicate.");
				}else if(CommonService.IsNullRString(value.getStatus()).equals("Z") && CommonService.IsNullRString(model.getStatus()).equals("A")){
					model.setStatus(value.getStatus());
				}
			}
			
			if(CommonService.IsNullRString(value.getStatus()).equals("A")){
				model.setCurrency("THB");
				model.setVoucherDate(CommonService.ConvertStringToDateTime(value.getDocDate()));
				model.setLivDoc(value.getLivDoc());
				model.setSupplierReference(value.getSupplierReference());
				model.setDocDate(CommonService.ConvertStringToDateTime(value.getDocDate()));
				model.setSupplierCode(value.getSupplierCode());
				
				model.setSupplierAmountLocal(CommonService.ConvertStringToBigDecimal(value.getNetAmount()));
				model.setTaxType(value.getTaxType());
				model.setCostOfGoodsLocal(CommonService.ConvertStringToBigDecimal(value.getCostOfGoodsLocal()));
				model.setVatAmount(CommonService.ConvertStringToBigDecimal(value.getVatAmountH()));
				
				model.setSyncExternalRefNo(value.getExtRefNo());
				model.setSyncExternalRefKey(value.getExtRefKey());
				model.setSyncIssync("Y");
				model.setStatus(value.getStatus());
				
				//Create By 
				model.setCreatedBy(value.getCreatedBy());
				model.setCreatedOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
				model.setLastUpdBy(value.getUpdatedBy());
				model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));					
				if(!CommonService.IsNull(value.getUpdatedBy())){
					model.setLastUpdBy(value.getCreatedBy());
					model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
				}
			}else if(CommonService.IsNullRString(value.getStatus()).equals("Z"))
			{
				//Updated On 
				model.setLastUpdBy(value.getUpdatedBy());
				model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));					
				if(!CommonService.IsNull(value.getUpdatedBy())){
					model.setLastUpdBy(value.getCreatedBy());
					model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
		
		return model;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:39:18 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param value_lst
	 * @throws Exception
	 */
	public void CreateToPromis(List<MmSuppdebitnotesinb> value_lst) throws Exception{
		try{
			AccountPayableVoucherServices AccountPayableVoucherServ = new AccountPayableVoucherServices(EmPromis);
			if(!CommonService.IsNull(value_lst)){
				
				//Check is Require field.
				IsRequireFields(value_lst);
				
				AccountPayableVoucher header = setHeader(value_lst.get(0));
				/*
				if(header != null ){
					if(CommonService.IsNullRString(header.getStatus()).equals("Z") && CommonService.IsNullRString(value_lst.get(0).getStatus()).equals("Z")){
						
					}
				}*/
				
				List<ProjectAccountCost> detail_lst = new ArrayList<ProjectAccountCost>();
				int seq = 0;
				for(MmSuppdebitnotesinb value : value_lst){
					seq++;
					ProjectAccountCostPK id = new ProjectAccountCostPK();
					id.setCompany(header.getId().getCompany());
					id.setProject(header.getId().getProject());
					id.setVoucherType(header.getId().getVoucherType());					
					id.setVoucherSeries(header.getId().getVoucherSeries());
					id.setVoucherNumber(header.getId().getVoucherNumber());
					id.setSeqNo(seq);
					
					//Check Exist ProjectAccountCost
					ProjectAccountCost detail = new ProjectAccountCostServices(EmPromis).findById(id);
					if(detail == null)
					{
						//New Object
						detail = new ProjectAccountCost();
						detail.setId(id);	
					}
					
					VwSyncGrnItem vwSyncGrnItem = FindGRNBudgetByUnit(detail.getId().getCompany(), detail.getId().getProject(), value.getRefNo(), value.getUnitNumber(), "A");
					if(vwSyncGrnItem != null){
						detail.setBuildingPhase(vwSyncGrnItem.getBuildingPhase());
						detail.setZoneCode(vwSyncGrnItem.getZoneCode());						
					}
					
					detail.setUnitNumber(value.getUnitNumber());
					
					//find Purchase Order 
					PurchaseModel purchaseModel = findPurchase(header.getId().getCompany(), header.getId().getProject(), value.getExtPoNo());
					detail.setPoType(purchaseModel.getPoType());
					detail.setPoSeries(purchaseModel.getPoSeries());
					detail.setPoNo(purchaseModel.getPoNo());
					detail.setPoRevision(purchaseModel.getRevisionNo());
					detail.setPoSeq(CommonService.ConvertStringToBigDecimal(value.getExtPoSeq()));
					
					//find Grn by Document No
					List<VwSyncGrnItem> grn_lst = new VwSyncGrnItemServices(EmPromis).findByDocumentNoWithoutSyncIsstaging(header.getId().getCompany(), header.getId().getProject(), value.getRefNo(), "A");
					if(!CommonService.IsNull(grn_lst)){
						VwSyncGrnItem goodsReceived = grn_lst.get(0);
						detail.setGrnType(goodsReceived.getGrnType());
						detail.setGrnSeries(goodsReceived.getGrnSeries());
						detail.setGrnNo(CommonService.ConvertStringToBigDecimal(goodsReceived.getGrnNo()));
						detail.setGrnSeqNo(CommonService.ConvertStringToBigDecimal(value.getGrnSeqNo()));
					}else {
						System.err.println("Error Goods Received No is Nothing.");
						throw new Exception("Error Goods Received No is Nothing.");
					}
					
					detail.setItemCode(value.getItemCode());
					detail.setQuantity(CommonService.ConvertStringToBigDecimal(value.getQuantity()));
					detail.setCostBfVat(CommonService.ConvertStringToBigDecimal(value.getCostBfVat()));
					detail.setTotalCost(CommonService.ConvertStringToBigDecimal(value.getTotalCost()));
					
					//Interface Std SyncExternalRefNo  ---------------------------------------------------------------------------------
					detail.setSyncExternalRefNo(value.getExtRefNo());
					detail.setSyncExternalRefKey(value.getExtRefKey());
					detail.setSyncIssync("Y");
					detail.setStatus(value.getStatus());
					
					//Create By 
					detail.setCreatedBy(value.getCreatedBy());
					detail.setCreatedOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
					detail.setLastUpdBy(value.getUpdatedBy());
					detail.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));					
					if(!CommonService.IsNull(value.getUpdatedBy())){
						detail.setLastUpdBy(value.getCreatedBy());
						detail.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
					}
					//END -------------------------------------------------------------------------------------------------------------------					
					detail_lst.add(detail);
				}

				if(CommonService.IsNullRString(header.getStatus()).equals("A")) //Insert
					AccountPayableVoucherServ.SaveH_D(header, detail_lst, true);
				else if(CommonService.IsNullRString(header.getStatus()).equals("Z")) //Update					
					AccountPayableVoucherServ.SaveH_D(header, null, false);
				
				//Update back to Staging
				List<MmSuppdebitnotesinb> vlauelist = new ArrayList<MmSuppdebitnotesinb>();
				for(MmSuppdebitnotesinb obj : value_lst)
				{
					obj.setPms57DocumentNo(	header.getId().getVoucherType() + "-" + 
											header.getId().getVoucherSeries() + "-" + 
											Utilitys.leftPad(header.getId().getVoucherNumber() + "", 6, "0"));
					obj.setPmsApVoucherType(header.getId().getVoucherType());
					obj.setPmsApVoucherSeries(header.getId().getVoucherSeries());
					obj.setPmsApVoucherNumber(header.getId().getVoucherNumber());
					
					obj.setIssync("Y");
					obj.setMsgCode("S");
					obj.setMsgDesc("Success");
					obj.setMsgActResult(null);
					vlauelist.add(obj);	
				}
				
				new MmSuppdebitnotesinbServices(EmSynchro).Updated(vlauelist);
				
			}else {
				System.err.println("List<MmSuppdebitnotesinb> List is Nothing.");
				throw new Exception("List<MmSuppdebitnotesinb> List is Nothing.");
			}
				
			
		}catch(Exception e)
		{
			e.printStackTrace();
			try{
				if(!CommonService.IsNull(value_lst))
				{
					List<MmSuppdebitnotesinb> MmSuppdebitnotesinb_lst = new ArrayList<MmSuppdebitnotesinb>();
					for(MmSuppdebitnotesinb obj : value_lst)
					{
						obj.setIssync("Y");
						obj.setMsgCode("E");
						obj.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
						obj.setMsgActResult(CommonService.CutString(e.getMessage(), 3500));
						
						MmSuppdebitnotesinb_lst.add(obj);
					}
					new MmSuppdebitnotesinbServices(EmSynchro).Updated(MmSuppdebitnotesinb_lst);
				}
			}catch(Exception ex){
				System.err.println(ex.getMessage());
				log.error(ex.getMessage());
				throw ex;
			}
			
			log.error(e.getMessage());
			System.err.println(e.getMessage());		
			throw e;
		}
	}

	/**
	 * Date =Nov 13, 2013 : 2:39:24 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param value_lst
	 * @throws Exception
	 */
	private void IsRequireFields(List<MmSuppdebitnotesinb> value_lst) throws Exception {
		String company = null;
		String project = null;
		String buildingPhase = null;
		String zoneCode = null;
		String unit_number = null;
		String um = null;
		String taxType = null;
		String supplierCode = null;
				
		for(MmSuppdebitnotesinb value : value_lst){
			if(CommonService.IsNull(value.getSapCompanyCode()))
				throw new Exception("The SAP_COMPANY_CODE is require.");
			else
			{
				Company companySrv = new CompanyServices(EmPromis).findBySapCompany(value.getSapCompanyCode());
				if(CommonService.IsNull(companySrv)){
					throw new Exception("Data not found SAP Company [" + value.getSapCompanyCode()+"]");
				}else
					company = companySrv.getCompany();
			}
			
			if(CommonService.IsNull(value.getSapPlantCode()))
				throw new Exception("The SAP_PLANT_CODE is require.");
			else
			{
				CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
				if(CommonService.IsNull(costProject)){
					throw new Exception("Data not found CostProject SAP plant [" + value.getSapPlantCode()+"]");
				}else
					project = costProject.getId().getProject();
			}
			
			if(CommonService.IsNull(value.getVoucherType()))
				throw new Exception("The VOUCHER_TYPE is require.");
			else{
				if(CommonService.IsNullRString(value.getVoucherType()).equals("AP") || CommonService.IsNullRString(value.getVoucherType()).equals("57")){
				}else 
					throw new Exception("Data not found POR_TYPE ["+ value.getVoucherType() +"].");
			}
			
			if(CommonService.IsNull(value.getDocDate()))
				throw new Exception("The DOC_DATE is require.");		
			
			if(CommonService.IsNull(value.getSupplierCode()))
				throw new Exception("The SUPPLIER_CODE is require.");
			else{
				SupplierMasterServices SupplierMasterSrv = new SupplierMasterServices(EmPromis);
				SupplierMaster SupplierMasterObj = SupplierMasterSrv.findById(value.getSupplierCode());
				
				if(!CommonService.IsNull(SupplierMasterObj))
					supplierCode = SupplierMasterObj.getSupplierCode();
				else
					throw new Exception("Data not found supplierCode="+ value.getSupplierCode() +".");
			}
			/*
			if(CommonService.IsNull(value.getUnitNumber()))
				throw new Exception("The unit is require.");
			*/
			
			if(CommonService.IsNull(value.getExtPoNo()))
				throw new Exception("The EXT_PO_NO is require.");
			
			if(CommonService.IsNull(value.getExtPoSeq()))
				throw new Exception("The EXT_PO_SEQ is require.");
			
			if(CommonService.IsNull(value.getQuantity()))
				throw new Exception("The QUANTITY is require.");
			
			if(CommonService.IsNull(value.getExtRefKey()))
				throw new Exception("The EXT_REF_KEY is require.");
			
			if(CommonService.IsNull(value.getExtRefNo()))
				throw new Exception("The EXT_REF_NO is require.");
			
			if(CommonService.IsNull(value.getCreatedOn()))
				throw new Exception("The CREATED_ON is require.");
			
			if(CommonService.IsNull(value.getCreatedBy()))
				throw new Exception("The CREATED_BY is require.");
			
			if(CommonService.IsNull(value.getExtPoSeq()))
				throw new Exception("The EXT_PO_SEQ is require.");
			
			if(CommonService.IsNull(value.getUpdatedOn()))
				throw new Exception("The UPDATED_ON is require.");
			
			if(CommonService.IsNull(value.getUpdatedBy()))
				throw new Exception("The UPDATED_BY is require.");
			
			if(CommonService.IsNull(value.getIssync()))
				throw new Exception("The ISSYNC is require.");
			
			if(CommonService.IsNull(value.getInstanceNo()))
				throw new Exception("The INSTANCE_NO is require.");
			
			if(CommonService.IsNull(value.getStatus()))
				throw new Exception("The STATUS is require.");
			else{
				if(value.getStatus().equals("Z") || value.getStatus().equals("A")){}
				else 
					throw new Exception("Data not found status=" + value.getStatus());
			}
			
			if(CommonService.IsNull(value.getInterfaceNo()))
				throw new Exception("The INTERFACE_NO is require.");
			
			if(CommonService.IsNull(value.getLivDoc()))
				throw new Exception("The LIV_DOC is require.");
			
			if(CommonService.IsNull(value.getTaxType()))
				throw new Exception("The TAX_TYPE is require.");
		}
		
		//----------------------------------------------------------------------
		List<MmSuppdebitnotesinb> newList = new ArrayList<MmSuppdebitnotesinb>();
		for(MmSuppdebitnotesinb value : value_lst){
			if(CommonService.IsNull(value.getSapCompanyCode()))
				throw new Exception("The SAP_COMPANY_CODE is require.");
			else
			{
				Company companySrv = new CompanyServices(EmPromis).findBySapCompany(value.getSapCompanyCode());
				if(CommonService.IsNull(companySrv)){
					throw new Exception("Data not found SAP Company [" + value.getSapCompanyCode()+"]");
				}else
					company = companySrv.getCompany();
			}
			
			if(CommonService.IsNull(value.getSapPlantCode()))
				throw new Exception("The SAP_PLANT_CODE is require.");
			else
			{
				CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
				if(CommonService.IsNull(costProject)){
					throw new Exception("Data not found CostProject SAP plant [" + value.getSapPlantCode()+"]");
				}else
					project = costProject.getId().getProject();
			}
			value.setCompany(company);
			value.setProject(project);
			newList.add(value);
		}		
		new MmSuppdebitnotesinbServices(EmSynchro).Updated(newList);
		
		return; 
	}
}

/**
 * 
 * @author Chatree Siangklom of Administrator
 * Date =Nov 13, 2013 : 2:39:38 PM 
 * CreateBy=Chatree Siangklom
 * 
 * PurchaseModel
 * TODO
 */
class PurchaseModel{
	
	private String company;
	private String project; 
	private String poType;
	private String poSeries; 
	private BigDecimal poNo; 
	private BigDecimal revisionNo; 
	private String status;
	private String documentNo;
	
	public PurchaseModel(String company, 
										String project, 
										String poType, 
										String poSeries, 
										BigDecimal poNo,
										BigDecimal revisionNo,
										String documentNo,
										String status){
		this.company = company;
		this.project = project;
		this.poType = poType;
		this.poSeries = poSeries;
		this.poNo = poNo;
		this.revisionNo = revisionNo;
		this.status = status;
	}	
	
	/**
	 * @return the documentNo
	 */
	public String getDocumentNo() {
		return documentNo;
	}



	/**
	 * @param documentNo the documentNo to set
	 */
	public void setDocumentNo(String documentNo) {
		this.documentNo = documentNo;
	}



	/**
	 * @return the company
	 */
	public String getCompany() {
		return company;
	}
	/**
	 * @param company the company to set
	 */
	public void setCompany(String company) {
		this.company = company;
	}
	/**
	 * @return the project
	 */
	public String getProject() {
		return project;
	}
	/**
	 * @param project the project to set
	 */
	public void setProject(String project) {
		this.project = project;
	}
	/**
	 * @return the poType
	 */
	public String getPoType() {
		return poType;
	}
	/**
	 * @param poType the poType to set
	 */
	public void setPoType(String poType) {
		this.poType = poType;
	}
	/**
	 * @return the poSeries
	 */
	public String getPoSeries() {
		return poSeries;
	}
	/**
	 * @param poSeries the poSeries to set
	 */
	public void setPoSeries(String poSeries) {
		this.poSeries = poSeries;
	}
	/**
	 * @return the poNo
	 */
	public BigDecimal getPoNo() {
		return poNo;
	}
	/**
	 * @param poNo the poNo to set
	 */
	public void setPoNo(BigDecimal poNo) {
		this.poNo = poNo;
	}
	/**
	 * @return the revisionNo
	 */
	public BigDecimal getRevisionNo() {
		return revisionNo;
	}
	/**
	 * @param revisionNo the revisionNo to set
	 */
	public void setRevisionNo(BigDecimal revisionNo) {
		this.revisionNo = revisionNo;
	}
	/**
	 * @return the status
	 */
	public String getStatus() {
		return status;
	}
	/**
	 * @param status the status to set
	 */
	public void setStatus(String status) {
		this.status = status;
	}	
}